<?php
namespace app\console\controller;
use app\model\Member as SelfModel;

use app\model\MemberIntegral;
use PhpOffice\PhpSpreadsheet\Cell\DataType;
use PhpOffice\PhpSpreadsheet\IOFactory;
use think\db\exception\DataNotFoundException;
use think\db\exception\DbException;
use think\db\exception\ModelNotFoundException;
use think\facade\Request;
use think\facade\Route;
use think\facade\View;
use think\facade\Db;
use think\facade\Cache;
use think\facade\Cookie;
use think\validate\ValidateRule;

class Member extends Base
{

   

    public function initialize()
    {
        parent::initialize();
        $this->model = "\app\model\Member";
        $this->controller = "app\console\controller\Member";
        $this->list_rows = 10;
        $this->order = ['id'=>'desc'];
    }
    public function index()
    {
        $param = Request::param();


//        $data = parentPath(79,'Member');
//      $data = array_reverse($data);
//       halt($data);
        $data = $this->model::withSearch(array_keys($param), $param)->order($this->order)->where($this->where)->paginate(['query' => $param, 'list_rows' => $this->list_rows])->each(function ($item, $key) {
            $item['parent_mobile'] = SelfModel::where('id',$item['parent_id'])->value('mobile');

        });

        $this->select();
        return View::fetch('', ['data' => $data,'count'=>$this->model::withSearch(array_keys($param), $param)->count(),'brokerage'=>$this->model::withSearch(array_keys($param), $param)->sum('brokerage'),'integral'=>$this->model::withSearch(array_keys($param), $param)->sum('integral')]);
    }
    public function my_son()
    {
        $param = Request::param();

//        $data = parentPath(79,'Member');
//      $data = array_reverse($data);
//       halt($data);
        $data = $this->model::withSearch(array_keys($param), $param)->order($this->order)->where($this->where)->paginate(['query' => $param, 'list_rows' => 500])->each(function ($item, $key) {
            $item['parent_mobile'] = SelfModel::where('id',$item['parent_id'])->value('mobile');

        });
        $this->select();
        return View::fetch('', ['data' => $data]);
    }

    public function my_parent()
    {

        $param = Request::param();

        $data = parentPath($param['member_id'],'Member');
        //$data = array_reverse($data);
        $ids = array_column($data, 'id');

        $data = $this->model::where('id','in',$ids)->orderField(
            "id",
            $ids,
"asc"
)->where($this->where)->paginate(['query' => $param, 'list_rows' =>500])->each(function ($item, $key) {
            $item['parent_mobile'] = SelfModel::where('id',$item['parent_id'])->value('mobile');

        });
        $this->select();

        return View::fetch('', ['data' => $data]);
    }
    /**
     * 积分充值
     */
    public function integral_recharge()
    {
        $param = $this->request->param();
        $validate = new \app\validate\Member;
        $result = $validate->scene('integral_recharge')->check($param);
        if(!$result) return ['code' => 400, 'msg' => $validate->getError()];

        $ret = MemberIntegral::saveData($param['member_id'],'后台充值','+',$param['integral']);
        if($ret === true){
            return json(['code'=>200,'msg'=>'充值成功']);
        }
        return json(['code'=>400,'msg'=>'失败']);
    }

    public function update_level(\think\Request $request)
    {
        $param = $this->request->param();

        $ret = SelfModel::where('id',$param['member_id'])->update(['level_id'=>$param['level_id']]);

        if($ret !== false){
            return json(['code' => 200, 'msg' => '会员级别修改成功']);
        }
        return json(['code' => 400, 'msg' => '失败']);
    }

    public function create_son()
    {
        Db::startTrans();
        try {
            $param = $this->request->param();
            $son = $this->request->param('son');
            if (empty($son)) {
                return json(['code' => 400, 'msg' => '请填写手机号']);
            }

            $dat = textAreaArray($son);
            $i=0;
            foreach ($dat as $mobile) {

                $find = SelfModel::where('mobile', $mobile)->find();
                if (!empty($find)) {
                    //return json(['code' => 400, 'msg' => $mobile . '已经注册']);
                }else{
                    $data['nickname'] = cache('web_name') . ' ' . randNum(4);
                    $data['headimgurl'] = cache('logo');
                    $data['parent_id'] = $param['parent_id'];
                    $data['level_id'] = $param['level_id'];
                    $data['mobile'] = $mobile;
                    $data['password'] = 384014;
                    //['mobile'=>$request->mobile,'invite_code'=> $request->invite_code,'parent_id'=>$parent_id]
                    $ret = SelfModel::create($data);
                    if($ret){
                        $i++;
                    }
                    $parent_team = parentPath($ret['id'], 'Member');
                    if (!empty($parent_team)) {
                        foreach ($parent_team as $v) {
                            SelfModel::where('id', $v['id'])->inc('team_count')->update();
                        }
                    }
                }


            }
            Db::commit();
            return json(['code' => 200, 'msg' => '会员批量注册成功 '.$i]);
        }  catch (\Exception $e) {
            Db::rollback();
            return json(['code' => 400, 'msg' => $e->getMessage()]);
        }

    }

    /*
     * 修改上级推荐人
     */
    public function update_parent()
    {
        $param = $this->request->param();
        $parent = SelfModel::where('mobile', $param['mobile'])->find();
        if(empty($parent)){
            return ['code' => 400, 'msg' => '推荐人手机号不正确'];
        }
        $ret = SelfModel::where('id',$param['member_id'])->update(['parent_id'=>$parent['id'],'parent_invite_code'=>$parent['invite_code']]);
        if($ret !== false){
            return ['code' => 200, 'msg' => '推荐人修改成功'];
        }
        return ['code' => 400, 'msg' => '推荐失败'];

    }

    //导出数据
    public static function export_data($data)
    {

    }

    public static function import_data($data){
        //导入数据
        win('导入成功');
    }

    public function export($filename='1.xlsx')
    {
        $filename = '会员导出';
        $param = $this->request->param();
        if(!empty($param['create_time'])){
            $filename .= ' '.$param['create_time'];
        }
        $filename .= '.xlsx';
        $spreadsheet = new \PhpOffice\PhpSpreadsheet\Spreadsheet();
        $sheet = $spreadsheet->getActiveSheet();
        $header = ['ID','邀请码','手机号','昵称','上级会员ID','上级邀请码','上级手机号','佣金余额','积分','会员级别','团队人数','创建时间','余额+积分'];
        foreach ($header as $kh => $vh){
            $sheet->setCellValueByColumnAndRow($kh+1,1, $vh);
        }
        $data = SelfModel::withSearch(array_keys($param), $param)->lock(true)->order(['id'=>'desc'])->select();
        foreach ($data as $k => $v){
            $sheet->setCellValueByColumnAndRow(1,1+$k+1, $v['id']);
            $sheet->setCellValueExplicitByColumnAndRow(2,1+$k+1, $v['invite_code'],DataType::TYPE_STRING);
            $sheet->setCellValueExplicitByColumnAndRow(3,1+$k+1, $v['mobile'],DataType::TYPE_STRING);
            $sheet->setCellValueExplicitByColumnAndRow(4,1+$k+1, $v['nickname'],DataType::TYPE_STRING);
            $sheet->setCellValueExplicitByColumnAndRow(5,1+$k+1, $v['parent_id'],DataType::TYPE_STRING);
            $sheet->setCellValueExplicitByColumnAndRow(6,1+$k+1, $v['parent_invite_code'],DataType::TYPE_STRING);
            $sheet->setCellValueExplicitByColumnAndRow(7,1+$k+1, $v['parent_mobile'],DataType::TYPE_STRING);
            $sheet->setCellValueByColumnAndRow(8,1+$k+1, $v['brokerage']);
            $sheet->setCellValueByColumnAndRow(9,1+$k+1, $v['integral']);
            $sheet->setCellValueExplicitByColumnAndRow(10,1+$k+1, $v['level_name'],DataType::TYPE_STRING);
            $sheet->setCellValueExplicitByColumnAndRow(11,1+$k+1, $v['team_count'],DataType::TYPE_STRING);
            $sheet->setCellValueExplicitByColumnAndRow(12,1+$k+1, $v['create_time'],DataType::TYPE_STRING);
            $sheet->setCellValueByColumnAndRow(13,1+$k+1,$v['brokerage']+$v['integral']);

        }
        header('Content-Type: application/vnd.ms-excel');
        header('Content-Disposition: attachment;filename="'.$filename.'"');
        header('Cache-Control: max-age=0');
        // If you're serving to IE 9, then the following may be needed
        header('Cache-Control: max-age=1');
        // If you're serving to IE over SSL, then the following may be needed
        header('Expires: Mon, 26 Jul 1997 05:00:00 GMT'); // Date in the past
        header('Last-Modified: ' . gmdate('D, d M Y H:i:s') . ' GMT'); // always modified
        header('Cache-Control: cache, must-revalidate'); // HTTP/1.1
        header('Pragma: public'); // HTTP/1.0

        $writer = IOFactory::createWriter($spreadsheet, 'Xlsx');
        $writer->save('php://output');
        $spreadsheet->disconnectWorksheets();
        unset($spreadsheet);
        ob_end_flush();

    }






}